package com.neusoft.ysu.his.service.impl;

import com.neusoft.ysu.his.entity.CommonResult;
import com.neusoft.ysu.his.entity.Manager;

import com.neusoft.ysu.his.mapper.ManagerMapper;
import com.neusoft.ysu.his.service.IManagerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

import static com.neusoft.ysu.his.util.JWTUtil.buildToken;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 作者：赵子鉴
 * @since 2023-08-29
 */
@Service
public class ManagerServiceImpl implements IManagerService {
    @Autowired
    ManagerMapper managerMapper;
    @Override
    public CommonResult insert(Manager manager) throws UnsupportedEncodingException {

//        System.out.println("manager"+manager);
        List<Manager> form_base=managerMapper.insertCheck(manager);

        CommonResult result=new CommonResult<>(form_base);
        System.out.println(form_base);
        if(form_base.size()!=0){
            result.setCode(202);
            result.setMsg("用户名已存在");
            return result;
        }
        else {
            int i = managerMapper.insert(manager);
            result.setResult(manager);
            result.setCode(200);
            result.setMsg("注册成功");
            return result;
        }


    }

    @Override
    public CommonResult loginCheck(Manager manager) throws UnsupportedEncodingException {
        System.out.println("manager"+manager);
        Manager form_base=managerMapper.loginCheck(manager);

        CommonResult result=new CommonResult<>(form_base);

        if(form_base!=null && form_base.getLoginname().equals(manager.getLoginname()) && form_base.getPassword().equals(manager.getPassword())
                && form_base.getDelmark()==0){
            result=new CommonResult<>(form_base);
            result.setMsg("登录成功！欢迎回来");
            HashMap<String,String> map=new HashMap<>();
            map.put("logname","admin");
            String token=buildToken(map);
            System.out.println("token:"+token);
            form_base.setToken(token);

            return result;
        }
        else {
            result.setCode(201);
            result.setMsg("用户名或密码不正确");
            return result;
        }
    }
}
